package com.libraryApp.service.impl;

import com.libraryApp.appCommon.ServiceResultEnum;
import com.libraryApp.appUtil.NumberUtil;
import com.libraryApp.appUtil.SystemUtil;
import com.libraryApp.appVo.UserLoginVo;
import com.libraryApp.entity.UserDo;
import com.libraryApp.entity.UserTokenDo;
import com.libraryApp.mapper.AppLoginMapper;
import com.libraryApp.service.appLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @CreateDate 2021-03-06
 * @Author yufang
 */
@Service
public class appLoginServiceImpl implements appLoginService {

    @Autowired
    AppLoginMapper appLoginMapper;

    @Override
    public String login(UserLoginVo vo) {
        UserDo user = appLoginMapper.selectByLoginNameAndPasswd(vo);
        if (user != null) {
            if (user.getLockedFlag() == 1) {
                return ServiceResultEnum.LOGIN_USER_LOCKED_ERROR.getResult();
            }
            //登录后即执行修改token的操作
            String token = getNewToken(System.currentTimeMillis() + "", user.getUserId());
            UserTokenDo UserTokenDo = appLoginMapper.getUserToken(user.getUserId());
            //当前时间
            Date now = new Date();
            //过期时间
            Date expireTime = new Date(now.getTime() + 2 * 24 * 3600 * 1000);//过期时间 48 小时
            if (UserTokenDo == null) {
                UserTokenDo = new UserTokenDo();
                UserTokenDo.setUserId(user.getUserId());
                UserTokenDo.setToken(token);
                UserTokenDo.setUpdateTime(now);
                UserTokenDo.setExpireTime(expireTime);
                //新增一条token数据
                if (appLoginMapper.insertUserToken(UserTokenDo) > 0) {
                    //新增成功后返回
                    return token;
                }
            } else {
                UserTokenDo.setToken(token);
                UserTokenDo.setUpdateTime(now);
                UserTokenDo.setExpireTime(expireTime);
                //更新
                if (appLoginMapper.updateUserToken(UserTokenDo) > 0) {
                    //修改成功后返回
                    return token;
                }
            }

        }
        System.out.println("ggggggggggggggggggggggggg");
        return ServiceResultEnum.LOGIN_ERROR.getResult();

    }

    /**
     * 获取token值
     *
     * @param timeStr
     * @param userId
     * @return
     */
    private String getNewToken(String timeStr, Long userId) {
        String src = timeStr + userId + NumberUtil.genRandomNum(4);
        return SystemUtil.genToken(src);
    }

}
